import { Body, Controller, Delete, Get, Post, Put, Query } from '@nestjs/common'
import { ApiOperation, ApiTags } from '@nestjs/swagger'

import { ApiResult } from '~/common/decorators/api-result.decorator'
import { ApiSecurityAuth } from '~/common/decorators/swagger.decorator'
import { DeleteDto } from '~/common/dto/delete.dto'
import { BusinessException } from '~/common/exceptions/biz.exception'
import { CreatorPipe } from '~/common/pipes/creator.pipe'
import { UpdaterPipe } from '~/common/pipes/updater.pipe'
import { ErrorEnum } from '~/constants/error-code.constant'
import { Pagination } from '~/helper/paginate/pagination'
import { definePermission, Perm } from '~/modules/system/auth/decorators/permission.decorator'
import { DictDataEntity } from '~/modules/system/dict-data/dict-data.entity'

import { DictDataQueryDto, DictDataSaveDto, DictDataSimpleDto } from './dict-data.dto'
import { DictDataService } from './dict-data.service'

export const permissions = definePermission('system:dict-data', {
  PAGE: 'page',
  QUERY: 'query',
  CREATE: 'create',
  UPDATE: 'update',
  DELETE: 'delete',
} as const)

@ApiTags('System - 字典数据模块')
@ApiSecurityAuth()
@Controller('dict-data')
export class DictDataController {
  constructor(private dictDataService: DictDataService) {}

  @Get('page')
  @ApiOperation({ summary: '获取字典数据分页列表' })
  @ApiResult({ type: [DictDataEntity], isPage: true })
  @Perm(permissions.PAGE)
  async page(@Query() dto: DictDataQueryDto): Promise<Pagination<DictDataEntity>> {
    return this.dictDataService.page(dto)
  }

  @Get('simple-list')
  @ApiOperation({ summary: '获取所有字典数据(不分页)' })
  @ApiResult({ type: [DictDataSimpleDto] })
  async list(@Query() dto: DictDataQueryDto): Promise<DictDataSimpleDto[]> {
    return this.dictDataService.getSimpleList(dto)
  }

  @Get('get')
  @ApiOperation({ summary: '查询字典数据详情' })
  @ApiResult({ type: DictDataEntity })
  @Perm(permissions.QUERY)
  async get(@Query('id') id: number): Promise<DictDataEntity> {
    return this.dictDataService.findOne(id)
  }

  @Get('get-by-type')
  @ApiOperation({ summary: '根据字典类型获取字典数据' })
  @ApiResult({ type: [DictDataEntity] })
  async getByType(@Query('dictType') dictType: string): Promise<DictDataEntity[]> {
    return this.dictDataService.getByDictType(dictType)
  }

  @Post('create')
  @ApiOperation({ summary: '创建字典数据' })
  @Perm(permissions.CREATE)
  async create(@Body(CreatorPipe) dto: DictDataSaveDto): Promise<void> {
    await this.dictDataService.create(dto)
  }

  @Put('update')
  @ApiOperation({ summary: '更新字典数据' })
  @Perm(permissions.UPDATE)
  async update(@Body(UpdaterPipe) dto: DictDataSaveDto): Promise<void> {
    if (!dto.id) {
      throw new BusinessException(ErrorEnum.REQUESTED_RESOURCE_NOT_FOUND)
    }
    await this.dictDataService.update(dto.id, dto)
  }

  @Delete('delete')
  @ApiOperation({ summary: '删除单个字典数据' })
  @Perm(permissions.DELETE)
  async delete(@Query('id') id: number): Promise<void> {
    if (!id || Number.isNaN(id)) {
      throw new BusinessException(ErrorEnum.REQUESTED_RESOURCE_NOT_FOUND)
    }

    await this.dictDataService.delete(id)
  }

  @Delete('delete-list')
  @ApiOperation({ summary: '批量删除字典数据' })
  @Perm(permissions.DELETE)
  async deleteList(@Query() dto: DeleteDto): Promise<void> {
    // 解析ids参数
    const ids = dto.ids.split(',').map(id => Number.parseInt(id.trim())).filter(id => !Number.isNaN(id))

    if (ids.length === 0) {
      throw new BusinessException(ErrorEnum.REQUESTED_RESOURCE_NOT_FOUND)
    }

    // 批量删除
    for (const id of ids) {
      await this.dictDataService.delete(id)
    }
  }
}
